<template>
  <div>
    <div class="app-container">
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="基础信息" name="first">
          <el-form
            ref="eform"
            v-loading="formLoading"
            :model="form"
            :rules="rules"
            label-width="110px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="登录账号" prop="loginName" :error="formError.code">
                  <el-input
                    v-model.trim="form.loginName"
                    maxlength="40"
                    :disabled="!isAdd"
                    autocomplete="off"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="密码" prop="password">
                  <el-col :span="18">
                    <el-input
                      v-model.trim="form.password"
                      maxlength="20"
                      :disabled="!isAdd"
                      type="password"
                      autocomplete="off"
                      placeholder="长度不能少于6"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-button v-if="!isAdd" type="success" @click="modifyPassword()">重置密码</el-button>
                  </el-col>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item v-if="isAdd" label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model.trim="form.confirmPassword"
                    type="password"
                    maxlength="20"
                    autocomplete="off"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名" prop="name" :error="formError.name">
                  <el-input v-model.trim="form.name" maxlength="40" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                    <el-radio :label="3">未知</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属部门" prop="departmentId">
                  <select-tree v-model="form.departmentId" default-expand-all :options="deptTreeOptions" />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item prop="positionIds" label="岗位">
                  <el-select v-model="form.positionIds" multiple>
                    <el-option
                      v-for="item in positionOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="职位状态" prop="state">
                  <el-select v-model="form.state" autocomplete="off">
                    <el-option
                      v-for="item in stateOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="入职日期" prop="jionday">
                  <el-date-picker
                    v-model="form.jionday"
                    type="date"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="账号状态" prop="status">
                  <el-select v-model="form.status">
                    <el-option label="正常" :value="1" />
                    <el-option label="停用" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="职务" prop="duty">
                  <el-input v-model.trim="form.duty" maxlength="40" />
                </el-form-item>
              </el-col>
            </el-row>
            <div class="user-auth-box">
              <div class="header">
                <span>权限:</span>
              </div>
              <el-form-item label="拥有角色" prop="roleIds">
                <el-checkbox-group v-model="form.roleIds">
                  <el-checkbox v-for="r in roleList" :key="r.id" :label="r.id">{{ r.name }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人信息" name="second">
          <el-form
            ref="mform"
            v-loading="formLoading"
            :model="mform"
            :rules="mrules"
            label-width="110px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="mform.birthday"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="idNo">
                  <el-input v-model.trim="mform.idNo" maxlength="45" autocomplete="off" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="最高学历" prop="eduLevel">
                  <el-select v-model="mform.eduLevel">
                    <el-option label="专科" value="专科" />
                    <el-option label="本科" value="本科" />
                    <el-option label="硕士研究生" value="硕士研究生" />
                    <el-option label="博士研究生" value="博士研究生" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业院校" prop="gradeSchool">
                  <el-input v-model.trim="mform.gradeSchool" maxlength="100" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业日期" prop="gradeDay">
                  <el-date-picker
                    v-model="mform.gradeDay"
                    type="date"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="手机号码" prop="mobile">
                  <el-input v-model.trim="mform.mobile" maxlength="20" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="telephone">
                  <el-input v-model.trim="mform.telephone" maxlength="30" autocomplete="off" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="电子邮件" prop="email">
                  <el-input v-model.trim="mform.email" maxlength="120" autocomplete="off" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="居住地址" prop="address">
                  <el-input v-model.trim="mform.address" maxlength="200" autocomplete="off" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div style="margin-left:160px;margin-top:30px;">
        <el-button type="primary" :disabled="disSubmit" @click="onSubmit">提 交</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </div>
    <!--表单组件-->
    <pswForm ref="pswform" />
  </div>
</template>

<script>
import request from '@/utils/request'
import { getTree } from '@/api/department'
import { getAllRoles } from '@/api/role'
import SelectTree from '@/components/SelectTree'
import pswForm from './password'
export default {
  name: 'UserForm',
  components: {
    SelectTree,
    pswForm
  },
  data: function() {
    var equalPsw = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      activeName: 'first',
      positionOptions: [],
      stateOptions: [{ id: 1, name: '在职' }, { id: 0, name: '离职' }],
      form: {
        id: null,
        name: '',
        loginName: '',
        email: '',
        duty: '',
        departmentId: null,
        confirmPassword: '',
        password: '',
        sex: 3,
        level: 15,
        state: 1,
        status: 1,
        roleIds: [],
        positionIds: []
      },
      mform: {
        telephone: '',
        jionday: '',
        mobile: '',
        address: '',
        birthday: '',
        idNo: '',
        eduLevel: '',
        gradeSchool: '',
        gradeDay: ''
      },
      defaultDeptTreeProps: {
        children: 'children',
        label: 'label'
      },
      formError: {
        name: null,
        code: null
      },
      rules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }],
        loginName: [{ required: true, message: '必填', trigger: 'blur' }],
        state: [{ required: true, message: '必填', trigger: 'blur' }],
        status: [{ required: true, message: '必填', trigger: 'blur' }],
        sex: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 6, message: '长度不能少于6', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '必填', trigger: 'blur' },
          { validator: equalPsw, trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '必填', trigger: 'change' }
        ]
      },
      mrules: {
        email: [
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        mobile: [{ pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }]
      },
      deptTreeOptions: [],
      roleList: [],
      formLoading: false,
      disSubmit: false,
      isAdd: true
    }
  },
  created() {
    // 先取得部门、角色，保证编辑时，显示初始值
    this.initDepartments()
    this.initRoles()
    this.initPositionOptions()
    if (this.$route.fullPath.indexOf('add') > 0) {
      this.isAdd = true
      this.form.roleIds = [2] // 默认 2=普通员工，最小权限角色
    } else { // edit...
      this.isAdd = false
      this.form.id = this.$route.params.id
      if (this.form.id) {
        this.initData(this.form.id)
      } else {
        this.$message.error('路由参数错误！')
        this.disSubmit = true
      }
    }
  },
  methods: {
    initDepartments() {
      getTree().then(data => {
        this.deptTreeOptions = data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    initRoles() {
      getAllRoles().then((data) => {
        this.roleList = data
      }).catch((e) => {
        this.$message.error('读取角色列表出错')
      })
    },
    initPositionOptions() {
      request({ url: '/sys/position/findList', method: 'post', data: {}}).then(data => {
        this.positionOptions = data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    initData(id) {
      this.formLoading = true
      request({ url: '/sys/user/' + id, method: 'get' })
        .then(data => {
          this.formLoading = false
          this.form = data
          // copy fields...
          Object.keys(this.mform).forEach(key => {
            if (typeof (data[key]) === 'undefined') {
              this.mform[key] = ''
            } else {
              this.mform[key] = data[key]
            }
          })

          // console.log(this.form)
        })
        .catch(function(e) {
          this.disSubmit = true
          this.$message.error('读取用户数据出错')
        })
    },
    onSubmit() {
      this.$refs['eform'].validate(valid => {
        if (valid) {
          this.$refs['mform'].validate((mvalid) => {
            if (mvalid) {
              // copy fields...
              Object.keys(this.mform).forEach(key => {
                this.form[key] = this.mform[key]
              })

              if (this.isAdd) {
                this.doAdd()
              } else {
                this.doEdit()
              }
            } else {
              if (this.activeName !== 'second') {
                this.activeName = 'second'
              }
            }
          })
        } else { // change tab
          if (this.activeName !== 'first') {
            this.activeName = 'first'
          }
        }
      })
    },
    doAdd() {
      this.formLoading = true
      const param = {}
      this.copyNotBlankField(this.form, param)
      request({ url: '/sys/user/add', method: 'post', data: param }).then(res => {
        this.$notify({
          title: '新增成功',
          type: 'success',
          duration: 2500
        })
        // this.$message.success('提交成功！')
        this.formLoading = false
        this.close()
      }).catch(err => {
        this.formLoading = false
        this.$message.error('新增错误！' + err.message)
        if (err.code === 20001) {
          this.formError.code = err.message
        } else if (err.code === 20002) {
          this.formError.name = err.message
        }
      })
    },
    doEdit() {
      this.formLoading = true
      const param = {}
      this.copyNotBlankField(this.form, param)
      request({ url: '/sys/user/update', method: 'post', data: param }).then(res => {
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        // this.$message.success('提交成功！')
        this.formLoading = false
        this.close()
      }).catch(err => {
        this.formLoading = false
        this.$message.error('修改错误！' + err.message)
        if (err.code === 20001) {
          this.formError.code = err.message
        } else if (err.code === 20002) {
          this.formError.name = err.message
        }
      })
    },
    close() {
      // close tagView
      const view = { 'path': this.$route.path, 'name': this.$route.name }
      this.$store.dispatch('tagsView/delView', view)
      return this.$router.push({ path: '/sys/userlist' })
    },
    onCancel() {
      this.close()
    },
    modifyPassword() {
      this.$refs.pswform.change(this.form.id)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
  .user-auth-box {
     margin-bottom:15px;
     border-radius: 4px;
    border: 1px solid #ebeef5;
    background-color:lemonchiffon;
    .header{
      padding:5px 10px;
      font-size: 14px;
      color:chocolate ;
    }
  }
  .dept-tree{
    max-height: 200px;
    overflow-y: scroll;
  }
</style>
